package com.woniu.order.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.common.utils.PageData;
import com.woniu.common.utils.ResponseData;
import com.woniu.order.controller.ZcxOrderController;
import com.woniu.order.dto.ZcxApplicationDto;
import com.woniu.order.dto.ZcxProductApplication;
import com.woniu.order.dto.ZsbPowerUserDto;
import com.woniu.order.feign.ZsbProductFeign;
import com.woniu.order.feign.ZsbUumsFeign;
import com.woniu.order.mapper.*;
import com.woniu.order.pojo.*;
import com.woniu.order.pojo.dto.ZcxCustomerOrderDTO;
import com.woniu.order.service.ZcxCustomerOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
* @author 张
* @description 针对表【zcx_customer_order(直接客户订单表)】的数据库操作Service实现
* @createDate 2024-11-22 16:29:48

 */
@Service
public class ZcxCustomerOrderServiceImpl extends ServiceImpl<ZcxCustomerOrderMapper, ZcxCustomerOrder>
    implements ZcxCustomerOrderService{

    @Resource
    private ZcxCustomerOrderMapper orderMapper;
    @Autowired
    private ZsbProductFeign zsbProductFeign;
    @Autowired
    private ZcxOrderApplicationMapper zcxOrderApplicationMapper;
    @Autowired
    private ZcxOrderApplicationProductMapper zcxOrderApplicationProductMapper;
    @Autowired
    private ZcxOrderDetailsMapper zcxOrderDetailsMapper;
    @Autowired
    private ZsbUumsFeign zsUumsFeign;

    @Autowired
    private ZcxUpdateRecordMapper zcxUpdateRecordMapper;


    @Override
    public ResponseData<?> queryList(PageData<ZcxCustomerOrderDTO> pageData) {
        PageHelper.startPage(pageData.getPageNum(),pageData.getPageSize());
        List<ZcxCustomerOrder> lists = orderMapper.queryOrderList(pageData.getParam());
        PageInfo pageInfo = new PageInfo(lists);
        return new ResponseData<>().ok(pageInfo);
    }

    @Override
    public ResponseData<?> queryAllProduct() {
        ResponseData<?> responseData = zsbProductFeign.queryAllProduct();
        return new ResponseData<>().ok(responseData.getData());
    }

    @Override
    public ResponseData<?> addApplication(ZcxApplicationDto zcxApplicationDto) {
        //创建一个参数用于存储所有产品总价格
        BigDecimal totalPrice = new BigDecimal(0);
        //把订单商品信息放入订单详情申请表
        List<ZcxProductApplication> productList = zcxApplicationDto.getProductList();
        for (ZcxProductApplication zcxProductApplication : productList) {
            ZcxOrderApplicationProduct applicationProduct = new ZcxOrderApplicationProduct();
            applicationProduct.setApplicationCode(zcxApplicationDto.getApplicationCode());
            applicationProduct.setOrderCode(zcxApplicationDto.getOrderCode());
            applicationProduct.setProductCode(zcxProductApplication.getProductCode());
            applicationProduct.setProductName(zcxProductApplication.getProductName());
            applicationProduct.setInventory(zcxProductApplication.getInventory());
            applicationProduct.setPlaceOrderNum(zcxProductApplication.getPlaceOrderNum());
            applicationProduct.setUnivalent(zcxProductApplication.getUnivalent());
            //计算单品总价
            BigDecimal price = zcxProductApplication.getUnivalent()
                    .multiply(new BigDecimal(zcxProductApplication.getPlaceOrderNum()));
            applicationProduct.setPrice(price);
            applicationProduct.setStatus("0");
            totalPrice = totalPrice.add(price);
            zcxOrderApplicationProductMapper.addApplicationProduct(applicationProduct);
        }
        System.out.println("总价格："+totalPrice);
        //放入订单申请表
        ZcxOrderApplication zcxOrderApplication = new ZcxOrderApplication();
        zcxOrderApplication.setApplicationCode(zcxApplicationDto.getApplicationCode());
        zcxOrderApplication.setOrderCode(zcxApplicationDto.getOrderCode());
        zcxOrderApplication.setStatus("1");
        zcxOrderApplication.setOrderType(zcxApplicationDto.getOrderType());
        zcxOrderApplication.setCustomerName(zcxApplicationDto.getCustomerName());
        zcxOrderApplication.setSalesCode(zcxApplicationDto.getSalesCode());
        zcxOrderApplication.setDepositAmount(zcxApplicationDto.getDepositAmount());
        zcxOrderApplication.setSpecialDiscount(zcxApplicationDto.getSpecialDiscount());
        zcxOrderApplication.setCreateTime(zcxApplicationDto.getCreateTime());
        zcxOrderApplication.setCreatePerson(zcxApplicationDto.getCreatePerson());
        zcxOrderApplication.setApplicationDate(zcxApplicationDto.getApplicationDate());
        zcxOrderApplication.setApplicationReason(zcxApplicationDto.getApplicationReason());
        //修改理由
        zcxOrderApplication.setUpdateReason(zcxApplicationDto.getUpdateReason());
        //根据销售code查询销售人员名称
        ZsbPowerUserDto zsbPowerUserDto = zsUumsFeign.queryByCode(zcxApplicationDto.getSalesCode());
        zcxOrderApplication.setSalespersonName(zsbPowerUserDto.getRealName());
        //付款方式
        ZcxCustomerOrder zcxCustomerOrder = orderMapper.queryOrderByCode(zcxApplicationDto.getOrderCode());
        zcxOrderApplication.setPayment(zcxCustomerOrder.getPayment());
        //是否免定金
        zcxOrderApplication.setDeposit(zcxCustomerOrder.getDeposit());
        //税额
        zcxOrderApplication.setTax(zcxCustomerOrder.getTaxAmount());

        //正常订单可以申请为特价订单，如果申请为特价，计算加入折扣
        String orderType = zcxApplicationDto.getOrderType();
        if ("0".equals(orderType)) {
            //计算订单总价
            zcxOrderApplication.setTotalPrice(totalPrice);
        }
        if ("1".equals(orderType)) {
//            如果是特价订单 ，总价*折扣
            totalPrice=totalPrice.multiply(zcxApplicationDto.getSpecialDiscount());
            zcxOrderApplication.setTotalPrice(totalPrice);
        }

        zcxOrderApplicationMapper.addOrderApplication(zcxOrderApplication);

        //修改订单状态 审批中
        ZcxCustomerOrder zcxCustomerOrder1 = new ZcxCustomerOrder();
        zcxCustomerOrder1.setOrderCode(zcxApplicationDto.getOrderCode());
        zcxCustomerOrder1.setStatus(2);
        zcxCustomerOrder1.setUpdatePerson(zcxApplicationDto.getSalespersonName());
        orderMapper.updateOrderByCode(zcxCustomerOrder1);

        //判断减库存还是加库存
        //根据code码查询订单详情表，查询出所有订单详情，遍历，对比订单详情中的数量，与订单申请中的数量进行对比，
        //如果原订单中有，则比对选择数量，如果大于，则减库存，如果小于，则加库存；如果原订单中没有，则添加该产品的库存
        List<ZcxOrderDetails> zcxOrderDetails =  zcxOrderDetailsMapper.queryOrderDetailByCode(zcxApplicationDto.getOrderCode());
//        for (ZcxOrderDetails zcxOrderDetail : zcxOrderDetails) {
//            for (ZcxProductApplication zcxProductApplication : productList) {
//                if (zcxOrderDetail.getProductCode().equals(zcxProductApplication.getProductCode())) {
//                    //相同，选择了同样的产品，判断数量 ，加减库存
//                    if (zcxOrderDetail.getPlaceOrderNum().equals(zcxProductApplication.getPlaceOrderNum())){
//                    }else {
//                    }
//                }else{
//                    //没有相同的，说明该产品被删除，则添加库存
//                }
//            }
//        }

        //回滚老产品表库存
        for (ZcxOrderDetails zcxOrderDetail : zcxOrderDetails) {
            String productCode = zcxOrderDetail.getProductCode();
            String placeOrderNum = zcxOrderDetail.getPlaceOrderNum();
            zsbProductFeign.rollbackStock(productCode,Integer.parseInt(placeOrderNum));
        }
        //减新产品表库存
        for (ZcxProductApplication zcxProductApplication : productList) {
            String productCode = zcxProductApplication.getProductCode();
            String placeOrderNum = zcxProductApplication.getPlaceOrderNum();
            zsbProductFeign.reduceStock(productCode,Integer.parseInt(placeOrderNum));
        }

        return new ResponseData<>().ok();
    }

    @Override
    public ResponseData<?> queryOrderApplicationList(PageData<ZcxOrderApplication> pageData) {
        PageHelper.startPage(pageData.getPageNum(),pageData.getPageSize());
        List<ZcxOrderApplication> lists = zcxOrderApplicationMapper.queryOrderApplicationList(pageData.getParam());
        PageInfo pageInfo = new PageInfo(lists);
        return new ResponseData<>().ok(pageInfo);
    }

    @Override
    public ResponseData<?> createSnowId() {
        Snowflake snowflake = IdUtil.getSnowflake();
        String snowId = "DUSQ"+snowflake.nextId();
        return new ResponseData<>().ok(snowId);
    }

    @Override
    public ResponseData<?> approve(ZcxUpdateRecord zcxUpdateRecord) {
        //审批通过
        if (zcxUpdateRecord.getStatus().equals("1")){
            //添加数据到审批记录表
            ZcxUpdateRecord zcxUpdateRecord1 = new ZcxUpdateRecord();
            zcxUpdateRecord1.setOrderCode(zcxUpdateRecord.getOrderCode());
            zcxUpdateRecord1.setApplicationCode(zcxUpdateRecord.getApplicationCode());
            zcxUpdateRecord1.setStatus(zcxUpdateRecord.getStatus());
            zcxUpdateRecord1.setOpinion(zcxUpdateRecord.getOpinion());
            zcxUpdateRecordMapper.addRecord(zcxUpdateRecord1);

            //修改审批表状态 审批状态
            ZcxOrderApplication zcxOrderApplication = new ZcxOrderApplication();
            zcxOrderApplication.setApplicationCode(zcxUpdateRecord.getApplicationCode());
            zcxOrderApplication.setStatus("2");
            zcxOrderApplicationMapper.updateOrderApplication(zcxOrderApplication);

            //把审批通过后的产品zcx_order_application_product，放到zcx_order_details表
            //通过修改申请编号，查询产品信息
            String applicationCode = zcxUpdateRecord.getApplicationCode();
            List<ZcxOrderApplicationProduct> zcxOrderApplicationProducts = zcxOrderApplicationProductMapper.queryOrderApplicationProduct(applicationCode);
            //查询订单详情表，状态最大的订单详情
            List<ZcxOrderDetails> zcxOrderDetails = zcxOrderDetailsMapper.queryOrderDetailByCode(zcxUpdateRecord.getOrderCode());
            // 找到最大状态值
            int maxStatus = 0;
            for (ZcxOrderDetails detail : zcxOrderDetails) {
                if (Integer.parseInt(detail.getStatus())> maxStatus) {
                    maxStatus = Integer.parseInt(detail.getStatus());
                }
            }
            maxStatus = maxStatus+1;
            //放到订单详情表
            for (ZcxOrderApplicationProduct zcxOrderApplicationProduct : zcxOrderApplicationProducts) {
                //创建订单详情对象 ,
                ZcxOrderDetails zcxOrderDetail = new ZcxOrderDetails();
                zcxOrderDetail.setOrderCode(zcxOrderApplicationProduct.getOrderCode());
                zcxOrderDetail.setProductCode(zcxOrderApplicationProduct.getProductCode());
                zcxOrderDetail.setProductName(zcxOrderApplicationProduct.getProductName());
                zcxOrderDetail.setInventory(zcxOrderApplicationProduct.getInventory());
                String placeOrderNum = zcxOrderApplicationProduct.getPlaceOrderNum();
                zcxOrderDetail.setPlaceOrderNum(placeOrderNum);
                zcxOrderDetail.setUnit("件");
                BigDecimal univalent = zcxOrderApplicationProduct.getUnivalent();
                zcxOrderDetail.setUnivalent(univalent);
                //销售单价*下单和数量
                BigDecimal price = univalent.multiply(BigDecimal.valueOf(Integer.parseInt(placeOrderNum)));
                zcxOrderDetail.setPrice(price);
                zcxOrderDetail.setStatus(String.valueOf(maxStatus));
                zcxOrderDetailsMapper.addOrderDetail(zcxOrderDetail);
            }
            //根据申请编号查申请信息
            ZcxOrderApplication zcxOrderApplication1 = zcxOrderApplicationMapper.queryOrderApplicationByCode(applicationCode);
            //把申请信息，修改进订单表
            ZcxCustomerOrder zcxCustomerOrder = new ZcxCustomerOrder();
            zcxCustomerOrder.setOrderCode(zcxOrderApplication1.getOrderCode());
            zcxCustomerOrder.setPayment(zcxOrderApplication1.getPayment());
            zcxCustomerOrder.setDeposit(zcxOrderApplication1.getDeposit());
            zcxCustomerOrder.setSalespersonCode(zcxOrderApplication1.getSalesCode());
            zcxCustomerOrder.setSalespersonName(zcxOrderApplication1.getSalespersonName());
            zcxCustomerOrder.setDepositAmount(zcxOrderApplication1.getDepositAmount());
            zcxCustomerOrder.setOrderType(Integer.valueOf(zcxOrderApplication1.getOrderType()));
            zcxCustomerOrder.setSpecialDiscount(zcxOrderApplication1.getSpecialDiscount());
            zcxCustomerOrder.setTotalPrice(zcxOrderApplication1.getTotalPrice());
            zcxCustomerOrder.setTaxAmount(zcxOrderApplication1.getTax());
            zcxCustomerOrder.setStatus(1);
            zcxCustomerOrder.setDisplayStatus(1);
            orderMapper.updateOrder(zcxCustomerOrder);
        }

        //审批不通过
        if (zcxUpdateRecord.getStatus().equals("2")){
        //回滚库存，把申请的zcx_order_application库存加回去，把原本zcx_order_details的库存剪掉

            //添加数据到审批记录表
            ZcxUpdateRecord zcxUpdateRecord1 = new ZcxUpdateRecord();
            zcxUpdateRecord1.setOrderCode(zcxUpdateRecord.getOrderCode());
            zcxUpdateRecord1.setApplicationCode(zcxUpdateRecord.getApplicationCode());
            zcxUpdateRecord1.setStatus(zcxUpdateRecord.getStatus());
            zcxUpdateRecord1.setOpinion(zcxUpdateRecord.getOpinion());
            zcxUpdateRecordMapper.addRecord(zcxUpdateRecord1);

            //修改申请表状态为  审批不通过
            ZcxOrderApplication zcxOrderApplication = new ZcxOrderApplication();
            zcxOrderApplication.setApplicationCode(zcxUpdateRecord.getApplicationCode());
            zcxOrderApplication.setStatus("3");
            zcxOrderApplicationMapper.updateOrderApplication(zcxOrderApplication);

            //修改 订单状态为 审批不通过
            ZcxCustomerOrder zcxCustomerOrder = new ZcxCustomerOrder();
            zcxCustomerOrder.setOrderCode(zcxUpdateRecord.getOrderCode());
            zcxCustomerOrder.setStatus(4);  //审批不通过状态
            orderMapper.updateOrder1(zcxCustomerOrder);

            //回滚申请表的库存
            List<ZcxOrderApplicationProduct> zcxOrderApplicationProducts = zcxOrderApplicationProductMapper.queryOrderApplicationProduct(zcxUpdateRecord.getApplicationCode());
            for (ZcxOrderApplicationProduct zcxOrderApplicationProduct : zcxOrderApplicationProducts) {
                String productCode = zcxOrderApplicationProduct.getProductCode();
                String placeOrderNum = zcxOrderApplicationProduct.getPlaceOrderNum();
                zsbProductFeign.rollbackStock(productCode,Integer.parseInt(placeOrderNum));
            }

            //减新订单详情的库存
            List<ZcxOrderDetails> zcxOrderDetails = zcxOrderDetailsMapper.queryOrderDetailByCode(zcxUpdateRecord.getOrderCode());
            // 找到最大状态值
            int maxStatus = Integer.MIN_VALUE;
            for (ZcxOrderDetails detail : zcxOrderDetails) {
                if (Integer.parseInt(detail.getStatus())> maxStatus) {
                    maxStatus = Integer.parseInt(detail.getStatus());
                }
            }
            //list存放状态最大的集合
            List<ZcxOrderDetails> maxStatusDetails = new ArrayList<>();
            for (ZcxOrderDetails zcxOrderDetail : zcxOrderDetails) {
                if (zcxOrderDetail.getStatus().equals(String.valueOf(maxStatus))) {
                    maxStatusDetails.add(zcxOrderDetail);
                }
            }

            //减新订单详情的库存
            for (ZcxOrderDetails zcxOrderDetail : maxStatusDetails) {
                String productCode = zcxOrderDetail.getProductCode();
                String placeOrderNum = zcxOrderDetail.getPlaceOrderNum();
                zsbProductFeign.reduceStock(productCode,Integer.parseInt(placeOrderNum));
            }

        }
        return new ResponseData<>().ok();
    }

}




